<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="updateImage"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isIMG = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isIMG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isIMG && isLt5M
    },
    updateImage(param) {
      // console.log(param)
      const cos = new COS({
        SecretId: 'AKIDtc7VlodFepnY7ZpreFcmhNo11pPmwrXy',
        SecretKey: 'FSQ9ewznMiqjNmV4QYS8cAWr9E5i7JH0'
      })
      cos.putObject({
        Bucket: 'lesama-1307848141' /* 必须 */,
        Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
        Key: param.file.name /* 文件名称，必须 */,
        StorageClass: 'STANDARD',
        Body: param.file /* 文件对象，必须 */
      }, (err, data) => {
        // console.log(err || data)
        if (data.statusCode === 200) {
          // 图片上传成功
          this.$emit('input', 'https://' + data.Location)
        } else {
          this.$message.error(err.Message)
        }
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

